package com.myk.game.gobangchess;

import com.myk.game.gobangchess.beans.ChessPlayingBean;
import com.myk.game.gobangchess.constants.Msger;
import com.myk.game.gobangchess.dates.AccountData;
import com.myk.game.gobangchess.dates.NotificationData;
import com.myk.game.gobangchess.dates.RoomData;
import com.myk.game.gobangchess.signs.CacheSign;
import com.myk.game.gobangchess.utils.DateTimeUtil;
import com.myk.game.gobangchess.utils.Pair;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PlayerMsgHandler {

    private final Player player;

    public PlayerMsgHandler(Player player) {
        this.player = player;
    }

    public void handlerMessage(String msg) {
        String type = Msger.getMsgType(msg);
        switch (type) {
            //保持存活
            case Msger.keepLive: {
                new Timer().schedule(new TimerTask() {
                    @Override
                    public void run() {
                        player.sendMessage(Msger.keepLive, "Ok");
                    }
                }, 200);
                break;
            }
            //玩家申请退出
            case Msger.requestLogout: {
                System.out.println(player.getNickNameOrTemp() + "");
                DataManager.playerLogout(player);
                player.recycle();
                break;
            }
            //请求进入房间
            case Msger.requestEnterRoom: {
                String value = Msger.getMsgValue(msg);
                Room room = DataManager.getRoomByName(value);
                if (room != null) {
                    if (room.getPlayerNum() < room.getPlayerMax()) {
                        room.playerEnter(player);
                    }
                    else {
                        player.sendMessage(Msger.enterRoomFailed, "该房间玩家数已达上限");
                    }
                }
                else {
                    player.sendMessage(Msger.enterRoomFailed, "房间不存在");
                }
                break;
            }
            //用户离开房间
            case Msger.requestLeaveRoom: {
                player.getEnteringRoom().playerLeaveRoom(player);
                break;
            }
            //请求成为下棋者
            case Msger.requestBeChessPlayer: {
                String side = Msger.getMsgValue(msg);
                if (side.equals("1")) {
                    if (player.getEnteringRoom().player_black == null) {
                        player.getEnteringRoom().setBlackPlayer(player); //成为黑棋手
                    }
                    else {
                        player.sendMessage(Msger.beChessPlayerFailed, player.getEnteringRoom().getBlackPlayerName() + "已在黑位");
                        player.sendMessage(Msger.refreshRoomInfo, player.getEnteringRoom().getRoomInfo()); //可能是网络问题没有及时刷新到，再更新一次
                    }
                }
                else if (side.equals("2")) {
                    if (player.getEnteringRoom().player_white == null) {
                        player.getEnteringRoom().setWhitePlayer(player); //成为白棋手
                    }
                    else {
                        player.sendMessage(Msger.beChessPlayerFailed, player.getEnteringRoom().getWhitePlayerName() + "已在白位");
                        player.sendMessage(Msger.refreshRoomInfo, player.getEnteringRoom().getRoomInfo()); //可能是网络问题没有及时刷新到，再更新一次
                    }
                }
                break;
            }
            //请求离开座位成为观众
            case Msger.requestLeaveSeat: {
                player.getEnteringRoom().playerLeaveSeat(player);
                break;
            }
            //请求落子
            case Msger.requestMoveLater: {
                String pos = Msger.getMsgValue(msg);
                int row = Integer.parseInt(pos.split(",")[0]);
                int col = Integer.parseInt(pos.split(",")[1]);
                player.getEnteringRoom().moveLater(player, row, col);
                break;
            }
            //请求认输
            case Msger.requestAdmitDefeat: {
                player.getEnteringRoom().admitDefeat(player);
                break;
            }
            //请求详细规则
            case Msger.requestChessRule: {
                String roomName = Msger.getMsgValue(msg);
                Room ruleRoom = DataManager.getRoomByName(roomName);
                if (ruleRoom != null) {
                    String ruleStr = ruleRoom.getRuleText();
                    if (ruleStr != null) {
                        player.sendMessage(Msger.showInfoDialog, ruleStr);
                    }
                    else {
                        player.sendMessage(Msger.showInfoDialog, "暂未编写详细规则。。。");
                    }
                }
                break;
            }
            //请求数据统计
            case Msger.requestChessStatistics: {
                String roomName2 = Msger.getMsgValue(msg);
                String statisticsInfo = DataManager.getRoomStatistics(roomName2, player.getAccount());
                player.sendMessage(Msger.showInfoDialog, statisticsInfo);
                break;
            }
            //用户发送的自定义按钮的请求
            case Msger.requestCustomBottomEvent: {
                String title = Msger.getMsgValue(msg);
                if (title != null && !"".equals(title)) {
                    if (player.getEnteringRoom() != null) {
                        CustomBottom cb = null;
                        for (CustomBottom customBottom : player.getCustomBottomList()) {
                            if (customBottom.getTitle().equals(title)) {
                                cb = customBottom;
                            }
                        }
                        if (cb != null) {
                            cb.getAction().event(player); //回调自定义按钮事件
                        }
                        else {
                            System.out.println(player.getNickName() + "触发了未监听的" + title + "按钮");
                        }
                    }
                    else {
                        System.out.println(player.getNickName() + "不在房间中却触发了" + title + "按钮");
                    }
                }
                else {
                    System.out.println(player.getNickName() + "触发了" + title + "按钮");
                }
                break;
            }
            //请求获取缓存标记具体内容
            case Msger.requestCacheSignContent: {
                String cacheName = Msger.getMsgValue(msg);
                if (player.getEnteringRoom() != null) {
                    CacheSign cacheSign = player.getEnteringRoom().getCacheSignByName(cacheName);
                    if (cacheSign != null) {
                        String cacheContent = cacheSign.getSignContent();
                        player.sendMessage(Msger.returnCacheSignContent, cacheContent);
                    }
                }
                break;
            }
            //请求所有未读的公告
            case Msger.requestNotifications: {
                String[] ids = Msger.getMsgValue(msg).split(";");
                for (String id : ids) {
                    String text = NotificationData.getActiveNotificationById(id); //根据id获取公告具体文本
                    if (text != null && !"".equals(text)) {
                        player.sendMessage(Msger.pushNotificationText, id + "&" + text);
                    }
                }
                break;
            }
            //客户端请求获取个人资料
            case Msger.requestUserInfo: {
                player.sendMessage(Msger.refreshUserInfo, AccountData.getPersonalCompletelyInfo(player.getAccount()));
                break;
            }
            //客户端请求获取个人代币流水
            case Msger.requestUserAmountFlow: {
                player.sendMessage(Msger.showInfoDialog, "后台暂未开发完成，敬请期待");
                break;
            }
            //客户端请求获取个人对弈统计
            case Msger.requestUserPlayingDetail: {
                //除了显示每个棋的，还要显示每个对手的各种统计信息
                player.sendMessage(Msger.showInfoDialog, "后台暂未开发完成，敬请期待");
                break;
            }
            //客户端请求获取今日登录玩家列表
            case Msger.requestLoginPlayerList: {
                String dataTime = DateTimeUtil.localDateTimeToStr(LocalDateTime.now(), DateTimeUtil.DATE_FORMAT);
                String names = AccountData.getThisDayLoginPlayers(dataTime);
                StringBuilder stringBuilder = new StringBuilder("今日登录用户：\n\n");
                if (names != null && !"-1".equals(names)) {
                    String[] nameArray = names.split("，");
                    for (String name : nameArray) {
                        stringBuilder.append("{{").append(name).append("@style=ul@click=").append(Msger.requestOtherPlayerInfo).append(":").append(name).append("}}").append("  ");
                    }
                }
                player.sendMessage(Msger.showInfoDialog, stringBuilder.toString().trim());
                break;
            }
            //客户端请求查看他人信息
            case Msger.requestOtherPlayerInfo: {
                //除了显示每个棋的，还要显示每个对手的各种统计信息
                String nickName = Msger.getMsgValue(msg);
                Account account = AccountData.getAccountByNickName(nickName);
                if (account == null) {
                    player.sendMessage(Msger.showInfoDialog, "未找到该用户信息");
                }
                else {
                    player.sendMessage(Msger.showInfoDialog, AccountData.getOtherPlayerInfo(account));
                }
                break;
            }
            //客户端请求名人堂信息
            case Msger.requestPlayerRankList: {
                List<Pair<Account, Pair<Integer, Long>>> allAccountList = AccountData.getAccountListInfoOrderByPlayedCount();
                if (allAccountList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    int i = 0;
                    for (Pair<Account, Pair<Integer, Long>> pair : allAccountList) {
                        i++;
                        Account account = pair.first;
                        Pair<Integer, Long> playingInfo = pair.second;
                        sb.append(i).append("、").append("{{").append(AccountData.getNickNameOrTemp(account)).append("@style=ul@click=").append(Msger.requestOtherPlayerInfo).append(":").append(account.getNickName()).append("}}").append("，下过").append(playingInfo.first).append("款棋，总计对弈").append(playingInfo.second).append("次\n");
                    }
                    player.sendMessage(Msger.showInfoDialog, "{{名人堂@color=#FFFF6633@scale=1.4}}\n" + sb.toString().trim().substring(0, sb.length() - 1));
                }
                else {
                    player.sendMessage(Msger.showInfoDialog, "暂无数据");
                }
                break;
            }
            //客户端请求热棋榜信息
            case Msger.requestRoomRankList: {
                List<ChessPlayingBean> allChessPayingList = RoomData.getAllChessPlayingList();
                allChessPayingList.sort((o1, o2) -> o2.getRecordList().size() - o1.getRecordList().size());
                if (allChessPayingList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    int i = 0;
                    for (ChessPlayingBean chessPlayingBean : allChessPayingList) {
                        i++;
                        Set<String> playerSet = new HashSet<>();
                        chessPlayingBean.getRecordList().forEach(playingRecordBean -> {
                            playerSet.add(playingRecordBean.getPlayerBlack());
                            playerSet.add(playingRecordBean.getPlayerWhite());
                        });
                        //《棋名》n名玩家共对弈x次
                        sb.append(i).append("、").append("《").append(chessPlayingBean.getChessName()).append("》").append(playerSet.size()).append("名玩家共对弈").append(chessPlayingBean.getRecordList().size()).append("次\n");
                    }
                    player.sendMessage(Msger.showInfoDialog, "{{热棋榜@color=#FFFF6633@scale=1.4}}\n" + sb.toString().trim().substring(0, sb.length() - 1));
                }
                else {
                    player.sendMessage(Msger.showInfoDialog, "暂无数据");
                }
                break;
            }
            //客户端请求戳一戳，传入1:黑方昵称，3:黑方倒计时，2:白方昵称，4:白方倒计时
            case Msger.requestPokePlayer: {
                String pos = Msger.getMsgValue(msg); //获取位置
                if (player.getEnteringRoom() != null) {
                    String source = player.getNickNameOrTemp();
                    Player target = (pos.equals("1") || pos.equals("3")) ? player.getEnteringRoom().player_black : player.getEnteringRoom().player_white;
                    if (target != null) {
                        player.getEnteringRoom().noticeAllBroadcast(source + "戳了戳" + target.getNickNameOrTemp());
                    }
                }
                break;
            }
            //客户端请求获取预设消息列表
            case Msger.requestDefMessageList: {
                if (player.getEnteringRoom() != null) {
                    player.sendMessage(Msger.refreshDefMessageList, player.getEnteringRoom().getDefMessageList());//获取玩家所在房间的预设消息列表，用配置文件配置，但是每个不同房间可以有自己独立的
                }
                else {
                    player.sendMessage(Msger.refreshDefMessageList, "-1");
                }
                break;
            }
            //客户端请求发送预设消息，传入消息no
            case Msger.requestSendDefMessage: {
                if (player.getEnteringRoom() != null) {
                    int no = Integer.parseInt(Msger.getMsgValue(msg));
                    String message = player.getEnteringRoom().getDefMessage(no);
                    if (message != null) {
                        player.getEnteringRoom().sendAllChatMessage(player, message);
                    }
                }
                break;
            }
            //客户端请求发送自定义文本消息
            case Msger.requestSendCustomMessage: {
                if (player.getEnteringRoom() != null) {
                    String message = Msger.getMsgValue(msg);
                    if (message != null) {
                        System.out.println(player.getNickName() + "发送了自定义消息：" + message);
                        player.getEnteringRoom().sendAllChatMessage(player, message);
                    }
                }
                break;
            }
            //客户端请求发送问题的自定义文本回答
            case Msger.requestAnswerAskInputInfo: {
                String value = Msger.getMsgValue(msg);
                String askId = value.split("&", 2)[0];
                String inputText = value.split("&", 2)[1];
                AskInput.getAsk(askId).receive(inputText);  //根据askId从注册中心中取回调接口传入inputText进行回调
                break;
            }

        }
    }
}
